package com.sxm.yiwei.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.jaeger.library.StatusBarUtil;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.AppManager;
import com.sxm.yiwei.activitis.MineMember;
import com.sxm.yiwei.beans.pinche.HttpHead;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.pinche.CarVerifyActivity;
import com.sxm.yiwei.pinche.PincheActivity;
import com.sxm.yiwei.tools.DialogMain;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.GetUiltsData;
import com.sxm.yiwei.views.CenterDialog;

import org.xutils.ex.HttpException;
import org.xutils.http.RequestParams;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener,GetUiltsData.CallBackUtilsInf, CenterDialog.OnCenterItemClickListener {
    protected Bundle savedInstanceState;
    public Context context;
    public ProgressDialog progressDialog;
    private int failure_code;
    private CenterDialog centerDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
        context = this;
        setStatusBar();
        AppManager.getAppManager().addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView();
        initView();
        initData();
        initListener();
    }
    /*
    * 设置状态栏
    * */
    public void setStatusBar(){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT){
            StatusBarUtil.setColor(this,getResources().getColor(R.color.colorbt),0);

        }
    }
    @Override
    public void onBackPressed() {
        finish();
    }
    public Toast toast;
    public void showToast(String text) {
        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
        }
        toast.show();
    }

    public void showToast(BaseActivity activity, String text) {
        if (toast == null) {
            toast = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
        }
        toast.show();
    }

    /**
     * 显示带图片的Toast
     * @param text  需要显示的文字
     * @param imgId 需要显示的图片
     */
    public void showImageToast(String text, int imgId) {
        Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        toast.setText(text);
        LinearLayout toastView = (LinearLayout) toast.getView();
        toastView.setGravity(Gravity.CENTER);
        ImageView toastImg = new ImageView(context);
        toastImg.setLayoutParams(new LinearLayout.LayoutParams(dp2px(25), dp2px(25)));
        toastImg.setScaleType(ImageView.ScaleType.FIT_XY);
        toastImg.setImageResource(imgId);
        toastView.addView(toastImg, 0);
        toast.show();
    }


    public void showToast(int textId) {
        showToast(getString(textId));
    }

    public BaseActivity getActivity() {
        return this;
    }

    public Intent getIntent(Class clazz) {
        return new Intent(context, clazz);
    }

    public void startIntent(Class clazz) {
        startActivity(getIntent(clazz));
    }

    public int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    protected void hideStatusBar() {
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;//隐藏状态栏, 定义全屏参数
        Window window = getWindow(); //获得当前窗体对象
        window.setFlags(flag, flag);//设置当前窗体为全屏显示
    }
    private long lastClickTime;
    /**
     * 实现连续点击两次才退出应用程序
     */
   /* public void exit() {
        if ((System.currentTimeMillis() - lastClickTime) > 2000) {
            showToast("再按一次退出" + context.getResources().getString(R.string.app_name));
            lastClickTime = System.currentTimeMillis();
        } else {
            ActivityCollector.removeAll();
            System.exit(0);
        }
    }*/

    @Override
    public void onClick(View v) {
        //继承了BaseActivity的类, 如果要使用返回关闭Activity的功能
        //需要在继承的Activity的onClick(View v)里写上super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_back:
                //R.id.back为标题左上角的返回控件
                onBackPressed();
                break;

            default:
                break;
        }
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        //将Activity实例从AppManager的堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }
    /*
    * 从sp获取请求头信息
    * */
    public HttpHead getHeadInfo(){
        SharedPreferences sp=getSharedPreferences("userlogin",Context.MODE_PRIVATE);
        Log.d("getHeadInfo",sp.getString("userId",""));
        return new HttpHead(sp.getString("token",""),sp.getString("appid",""),sp.getString("userId",""),"application/json");
    }
    /*
    * 加载布局
    * */
    public  void setContentView(){};
    /*
    * 初始化视图
    * */
    public abstract void initView();
    /*
    * 初始化监听
    * */
    public abstract void initListener();
    /*
    * 初始化数据
    * */
    public abstract void initData();
    /*
    * 请求成功并且status=1
    * */
    @Override
    public void onSuccess(String result,String fromWhere) {
        progressDialog.dismiss();
        Log.d(fromWhere,result);
    }
    /*
    * 请求失败
    * */
    @Override
    public void onError(Throwable ex) {
        progressDialog.dismiss();
        showToast(ex.toString());
        Log.d("onError",ex.toString());
        if (ex instanceof HttpException){
            showToast("服务器链接断开");
        }else {

        }
    }
    /*
    * 请求成功错误码
    * */
    @Override
    public void onSuccessError(String result, String fromWhere) {
        progressDialog.dismiss();
        Log.d("fromWhere",result);
        JSONObject object = JSON.parseObject(result);
        String status = object.getString("status");
        if (!status.equals("1")){
            String failure = object.getString("failure");
            showToast("failure="+failure);
            ErrType.successErrCode(failure,context);

            if (failure.equals("1067")){
                failure_code= Constant.NAME_VERIFYING;
                showCenterDialog("您的实名认证正在审核中,感谢您的耐心等待","返回","确定");
            }else if (failure.equals("1068")){
                failure_code=Constant.NAME_NOT_VERIFY;
                showCenterDialog("为保证乘客的安全以及您的权益,车主需要实名认证后才可发布","返回","立即认证");

            }else if (failure.equals("1069")){
                failure_code=Constant.NAME_VERIFY_FALSE;
                showCenterDialog("您的实名认证未通过,请重新提交认证材料","返回","重新提交");

            }else if (failure.equals("1070")){
                failure_code=Constant.CAR_VERIFYING;
                showCenterDialog("您的车辆认证正在审核中,感谢您的耐心等待","返回","确定");

            }else if (failure.equals("1071")){
                failure_code=Constant.CAR_VERIFY_FALSE;
                showCenterDialog("您的车辆认证未通过,请重新提交认证材料","返回","重新提交");

            }else if (failure.equals("1066")){
                failure_code=Constant.CAR_NOT_VERIFY;
                showCenterDialog("您还没有进行车辆认证,车辆认证通过后才可抢单","返回","去认证");
            }else if (failure.equals("1082")){
                showToast("订单已超时");
                DialogMain.tipDialog("订单已超时");
            }else if (failure.equals("1088")){
                showToast("抱歉，您的赔付金额不合法");
                DialogMain.tipDialog("抱歉，您的赔付金额不合法");
            }else if (failure.equals("1089")){
                showToast("抱歉，您的退还金额不合法");
                DialogMain.tipDialog("抱歉，您的退还金额不合法");

            }else if (failure.equals("1076")){
                showToast("总价金额不合法");
                DialogMain.tipDialog("总价金额不合法");

            }else if (failure.equals("1087")){
                showToast("已过出发时间");
                DialogMain.tipDialog("已过出发时间");
            }else if (failure.equals("1072")){
                DialogMain.tipDialog("不能购买自己发布的服务哦");
            }
        }

    }
    /*
    * post请求
    * */
    public void httpPost(String url,JSONObject object,String fromWhere){
        progressDialog = ProgressDialog.show(this,"加载","正在加载中...");
        GetUiltsData.xPostMethod(getParamsPost(url,object),this,this,fromWhere);
    }
    /*
    * get请求
    * */
    public void httpGet(String url,JSONObject object,String fromWhere){
        progressDialog = ProgressDialog.show(this,"加载","正在加载中...");
        GetUiltsData.xGetMethod(getParamsGet(url,object),this,this,fromWhere);
    }
    /*
    * post请求头
    * */
    private RequestParams getParamsPost(String url, JSONObject object){
        RequestParams params = new RequestParams(url);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        params.setBodyContent(object.toJSONString());
        return params;
    }
    /*
    * get请求头
    * */
    private RequestParams getParamsGet(String url, JSONObject object){
        RequestParams params = new RequestParams(url);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        params.addParameter("params",object.toJSONString());
        return params;
    }
    /*
    * 时间选择器
    * */
    public void showIOSDate(final TextView textView, TimePickerView.Type type, String title, final int flag){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH,+20);
        TimePickerView pvTime = new TimePickerView.Builder(BaseActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                String time = getTime(date2,flag);
                textView.setText(time);
            }
        })
                .setType(type)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(getResources().getColor(R.color.textcolors))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.textcolorh))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.textcolorh))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.colorbg))//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
               // .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间
                //calendar.add(Calendar.DAY_OF_MONTH,-1);
                        .setRangDate(Calendar.getInstance(),instance)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();

    }
    /*
    *格式化时间
    * */
    public String getTime(Date date ,int type) {//可根据需要自行截取数据显示
        SimpleDateFormat format = null;
        if (type==1){
             format = new SimpleDateFormat("yyyy-MM-dd");
        }else if (type==0){
            format = new SimpleDateFormat("HH:mm");
        }else if (type==2){
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }

        return format.format(date);
    }
    /*
    * 提示框
    * */
    private void showCenterDialog(String text,String negative,String positive) {
        centerDialog = new CenterDialog(this, R.layout.dialog_layout, new int[]{R.id.dialog_cancel, R.id.dialog_sure});
        centerDialog.setOnCenterItemClickListener(this);
        centerDialog.show();
        TextView dialog_sure = (TextView) centerDialog.findViewById(R.id.dialog_sure);
        TextView dialog_cancel = (TextView) centerDialog.findViewById(R.id.dialog_cancel);
        TextView dialog_text = (TextView) centerDialog.findViewById(R.id.dialog_text);
        dialog_sure.setText(positive);
        dialog_cancel.setText(negative);
        dialog_text.setText(text);
    }
    /*
    * 提示框回调
    * */
    @Override
    public void OnCenterItemClick(CenterDialog dialog, View view) {
        switch (view.getId()){
            case R.id.dialog_sure:
                switch (failure_code){
                    case Constant.NAME_VERIFYING:
                        dialog.cancel();

                        break;
                    case Constant.NAME_NOT_VERIFY:
                        startActivity(new Intent(this, MineMember.class));
                        break;
                    case Constant.NAME_VERIFY_FALSE:
                        startActivity(new Intent(this, MineMember.class));

                        break;
                    case Constant.CAR_VERIFYING:
                        dialog.cancel();

                        break;
                    case Constant.CAR_VERIFY_FALSE:
                        startActivity(new Intent(this,CarVerifyActivity.class));
                        break;
                    case Constant.CAR_NOT_VERIFY:
                        startActivity(new Intent(this,CarVerifyActivity.class));

                        break;
                    default:
                        break;
                }
                break;
            default:
                dialog.cancel();
                break;
        }
    }



}
